<?php
if(!defined("IN_PHPSCUP"))exit("hacking");

class SCup_mysql
{
	var $conn_id = '';
	
	var $db_name = '' ;
	
	var $db_pwd = '' ;
	
	var $nowtime= '' ;
	
	var $db_host= '' ;
	
	var $db_user= '' ;

	var $pconnect= 0 ;

	var $charset= '' ;

	var $db_prefix= '' ;
	
    var $version  = '';

	var $querynum = 0;
	
	var $querytime = 0;
	
     function __construct($dbhost ='', $dbuser ='', $dbpw ='', $dbname = '',$dbprefix = '' ,$pconnect = 0, $charset = '')
    {
        $this->SCup_mysql($dbhost, $dbuser, $dbpw, $dbname,$dbprefix ,$pconnect, $charset);
    }

    function SCup_mysql($dbhost ='', $dbuser = '', $dbpw = '', $dbname = '',$dbprefix = '' ,$pconnect = 0, $charset = '')
    {
        $this->db_name      = !empty($dbname)?$dbname:DB_NAME;
		
        $this->db_pwd       = !empty($dbpw)?$dbpw:DB_PWD;
		
        $this->nowtime      = time();
		
        $this->db_host      = !empty($dbhost)?$dbhost:DB_HOST;
		
        $this->db_user      = !empty($dbuser)?$dbuser:DB_USER;
		
        $this->pconnect     = !empty($pconnect)?$pconnect: DB_PCONNECT;
		
        $this->charset      = !empty($charset)?$charset:DB_CHARSET;
		
        $this->db_prefix    = !empty($dbprefix)?$dbprefix:DB_PREFIX;
				
		
    }


	function connect()
	{
        if ($this->pconnect)
        {
            if (!($this->conn_id = @mysql_pconnect($this->db_host, $this->db_user, $this->db_pwd)))
            {
               $this->err_msg('Can not connect to MySQL server');
                return false;
            }
        }
        else
        {
            if (!($this->conn_id = @mysql_connect($this->db_host, $this->db_user, $this->db_pwd)))
            {
               $this->err_msg('Can not connect to MySQL server');
                return false;
            }
             
        }
		
		$this->version=$this->version() ;
		

       if ($this->version > '4.1')
        {
			$mysql_serverset="";		
            if ($this->charset)
            {
				 $mysql_serverset ="character_set_connection='$this->charset',character_set_results='$this->charset',character_set_client=binary" ;
				
            }
			
            if ($this->version > '5.0.1')
            {   
			    if(!empty($mysql_serverset))
				{
				$mysql_serverset.=',';
				}
			    $mysql_serverset.=" sql_mode='' ";
				
            }
			
			if(!empty($mysql_serverset))
			{
			    mysql_query("SET $mysql_serverset", $this->conn_id);
			}
			
			
        }
		

		if($this->db_name && !$this->select_db($this->db_name))
		{

            $this->err_msg('Cannot use database '.$this->db_name);
			
			return false;
		}

		return $this->conn_id;		
		
		
	}
	
    function query($sql, $type = '')
	{
	     if ($this->conn_id === NULL)
        {
            $this->connect();
        }
		
        /* 当当前的时间大于类初始化时间的时候，自动执行 ping 这个自动重新连接操作 */
        if ($this->version >= '4.3' && time() > $this->nowtime + 1)
        {
            mysql_ping($this->conn_id);
        }	

		//分析统计查询时间
		$speed_headtime=explode(' ',microtime());
		
		$speed_headtime=$speed_headtime[0]+$speed_headtime[1];	

		if($type == 'UNBUFFERED')
		{ 
		      if(!$query = mysql_unbuffered_query($sql , $this->conn_id))
			  {
			  	    $this->err_msg('MySQL Query Error', $sql);
			        return false;
			  }		
		}
		else
		{
		      if(!$query = mysql_query($sql , $this->conn_id))
			  {
			  	    $this->err_msg('MySQL Query Error', $sql);
			        return false;
			  }				
		
		}

		//分析统计查询时间
		$speed_endtime=explode(' ',microtime());
		$totaltime=number_format((($speed_endtime[0]+$speed_endtime[1]-$speed_headtime)/1),6);
		$this->querytime = $this->querytime + $totaltime;
	
		$this->querynum++;
		return $query; 
	

	}


	function get_one($sql, $type = '')
	{	
		$query = $this->query($sql, $type);
		$rs = $this->fetch_array($query);
		$this->free_result($query);
		return $rs ;
	}		
    

    function get_all($sql,$choose='')
    {    
	    $array = array();
        $result = $this->query($sql);           
        while ($row = $this->fetch_array($result))
        {
				  if(!empty($choose))
			      {
				  
				  $key = $row[$choose];
				  $array[$key] = $row;
				  
			      }
			      else
			     {
				  $array[] = $row;
				
			     }
			    
        }
		
		$this->free_result($result);
        return $array;
       
    }



	function check_fields($tablename, $array)
	{
		$fields = $this->get_fields($tablename);

		foreach($array AS $k=>$v)
		{
			if(!in_array($k,$fields))
			{
/*				$this->err_msg('MySQL Query Error', "Unknown column '$k' in field list");*/
				return false;
			}
		}
	}

	function get_fields($tablename)
	{
		$fields = array();
		$result = $this->query("SHOW COLUMNS FROM $tablename");
		while($r = $this->fetch_array($result))
		{
			$fields[] = $r['Field'];
		}
		$this->free_result($result);
		return $fields;
	}

    //获取特定表的信息
    function get_table_fields($tablename)
    {
       return mysql_fetch_field(mysql_list_fields($this->db_name,$tablename,$this->conn_id));
    }

	function table_status($table)
	{
		return $this->get_one("SHOW TABLE STATUS LIKE '$table'");
	}

	function tables()
	{
		$tables = array();
		$result = $this->query("SHOW TABLES");
		while($r = $this->fetch_array($result))
		{
			$tables[] = $r['Tables_in_'.$this->db_name];
		}
		$this->free_result($result);
		return $tables;
	}

	function table_exists($table)
	{
		$tables = $this->tables($table);
		return in_array($table, $tables);
	}

	function field_exists($table, $field)
	{
		$fields = $this->get_fields($table);
		return in_array($field, $fields);
	}

	function list_tables($dbname)
	{
/*		$tables = array();
		$result = $this->query("SHOW TABLES");
		while($r = $this->fetch_array($result))
		{
			$tables[] = $r['Tables_in_'.$dbname];
		}
		$this->free_result($result);
		return $tables;	*/ 
		return $this->query("SHOW TABLES FROM {$dbname}");;
		 
		//return mysql_list_tables($dbname, $this->conn_id);
	}
	
	
    function select_db($dbname)
    {
        return @mysql_select_db($dbname, $this->conn_id);
    }
	
    
	function version()
	{
		return mysql_get_server_info($this->conn_id);
	}
	
	
	function fetch_array($query, $result_type = MYSQL_ASSOC)
	{
		return mysql_fetch_array($query, $result_type);
	}

	function affected_rows()
	{
		return mysql_affected_rows($this->conn_id);
	}

	function num_rows($query)
	{
		return mysql_num_rows($query);
	}

	function num_fields($query)
	{
		return mysql_num_fields($query);
	}

	function result($query, $row)
	{
		return @mysql_result($query, $row);
	}

	function free_result(&$query)
	{
		return mysql_free_result($query);
	}

	function insert_id()
	{
		return mysql_insert_id($this->conn_id);
	}

	function fetch_row($query)
	{
		return mysql_fetch_row($query);
	}

	function close()
	{
		return mysql_close($this->conn_id);
	}

	function error()
	{
		return @mysql_error($this->conn_id);
	}

	function errno()
	{
		return intval(@mysql_errno($this->conn_id)) ;
	}

    function escape($str)
	{
		if(function_exists('mysql_real_escape_string'))
		{
			return htmlspecialchars(mysql_real_escape_string($str, $this->conn_id));
		}
		return htmlspecialchars(addslashes($str));
    }


	function err_msg($msg,$sql='')
	{

/*       if (defined("IS_PHPSCUP_ADMIN")||IS_DEBUG) 
       {
		 $notice = & get_message(array('msg'=>"<b>SCUP info : </b>$msg<br /><b>MySQL Query : </b>$sql <br /><b> MySQL Error : </b>".$this->error()." <br /> <b>MySQL Errno : </b>".$this->errno(),'url'=>'','title'=>'Notice','skip_time'=>'40000'));
		 $notice ->display();	
       }
*/

		echo "<b>SCUP info : </b>$msg<br /><b>MySQL Query : </b>$sql <br /><b> MySQL Error : </b>".$this->error()." <br /> <b>MySQL Errno : </b>".$this->errno();		
		exit;
		
	}


}



?>